import { Button, Col, Form, Input, Row, message } from 'antd';
import { UserOutlined, LockOutlined, MailOutlined } from '@ant-design/icons';
import { useState, ChangeEvent } from 'react';
import { sendCode, Register as Rs } from '../../../api/User';
import { useNavigate } from 'react-router-dom';
import { Footer } from "antd/es/layout/layout"
const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 10,
      offset: 0,
    },
    sm: {
      span: 16,
      offset: 8,
    },
  },
}
    
function Register() {
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [confirmPassword, setConfirm] = useState('')
  const [email, setEmail] = useState('')
  const [code, setCode] = useState('')
  const [btnText, setBtnText] = useState('发送验证码')
  const [btnBool, setBtnBool] = useState(false)
  const navigate = useNavigate()
  const backImg = `https://img.zcool.cn/community/01255258f41ec8a8012049ef106d6e.jpg@2o.jpg`
  const NameChange = (event: ChangeEvent) => {
    setUsername((event.target as HTMLInputElement).value)
  }
  const PasswordChange = (event: ChangeEvent) => {
    setPassword((event.target as HTMLInputElement).value)
  }
  const ConfirmChange = (event: ChangeEvent) => {
    setConfirm((event.target as HTMLInputElement).value)
  }
  const EmailChange = (event: ChangeEvent) => {
    setEmail((event.target as HTMLInputElement).value)
  }
  const CodeChange = (event: ChangeEvent) => {
    setCode((event.target as HTMLInputElement).value)
  }


  //表单提交成功时调用
  const onFinish = async (values: any) => {
    Rs(username, password, email,code ).then(res => {
     if(res.data.code==200){
      message.success('注册成功！')
      //测试！！！！！！！！！！！！
      console.log(res);
       navigate('/Login')
     }
     else{
      message.error(res.data.message)
     }
    })
  }
  //这个函数会在表单提交失败时被调用
  const onFinishFailed = (errorInfo: any) => {
    message.error(errorInfo.errorFields[0].errors[0])
  };

  //发送验证码 已验证成功
  const getCode = (event: ChangeEvent) => {
    sendCode(email).then(res => {
      message.success('验证码已发送！')
    })
    let maxTime = 10
    const timer = setInterval(() => {
      if (maxTime > 0) {
        maxTime--
        setBtnText('重新获取' + maxTime + 's')
        setBtnBool(true)
      }
      else {
        setBtnText('发送验证码')
        setBtnBool(false)
      }
    }, 1000)
  }


  return (
    <div style={{
      position: "fixed",
      width: "100%",
      height: "100%",
      backgroundImage: `url(${backImg})`

    }}>
      <div style={{
        width: "450px",
        margin: '15vh auto',
        textAlign: 'center',
        backgroundColor: "rgb(255,255,255)",
        border: "solid  rgb(231,232,234) 3px",
        borderRadius: '15px'
      }}>
        <h1 style={{
          fontWeight: "normal"
        }}>欢 迎 注 册</h1>
        <Form labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 350, }}
          autoComplete="off"
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
          {/*用户名 */}
          <Form.Item
            label="用户名："
            name="username"
            rules={[
              {
                required: true,
                message: '请输入你的用户名'
              },
              {
                pattern: /^.{6,12}$/,
                message: '用户名在6-12个字符之间'
              }]}
          >
            <Input prefix={< UserOutlined />} placeholder="userName"
              defaultValue={username}
              onChange={NameChange}

            />
          </Form.Item>
          {/* 密码 */}
          <Form.Item name="password" label="密码"
            rules={[
              {
                required: true, message: '请输入你的密码!',
              },
              {
                pattern: /^.{6,20}$/,
                message: '密码在6-20位之间'
              },
              {
                pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/,
                message: '密码需同时包含数字和字母'
              }
            ]}
            hasFeedback
          >
            <Input.Password prefix={<LockOutlined />} placeholder="password"
              defaultValue={password}
              onChange={PasswordChange} />
          </Form.Item>
          {/* 确认密码 */}
          <Form.Item
            name="confirm"
            label="确认密码"
            dependencies={['password']}
            hasFeedback
            rules={[
              {
                required: true,
                message: '请确认密码!',
              },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('与原密码不一致'));
                },
              }),
            ]}
          >
            <Input.Password prefix={<LockOutlined />} placeholder="confirmPassword"
              defaultValue={confirmPassword}
              onChange={ConfirmChange} />
          </Form.Item>
          {/* 邮箱 */}
          <Form.Item name="email" label="邮箱"
            rules={[
              {
                type: 'email',
                message: '请输入有效的邮箱!',
              },
              {
                required: true,
                message: '请输入你的邮箱!',
              },
            ]}
          >
            <Input prefix={<MailOutlined />} placeholder="email"
              defaultValue={email}
              onChange={EmailChange} />
          </Form.Item>
          {/* 验证码 */}
          <Form.Item label="验证码">
            <Row gutter={8}>
              <Col span={10}>
                <Form.Item
                  name="captcha"
                  noStyle
                  rules={[{ required: true, message: '请输入你收到的验证码！' }]}
                >
                  <Input defaultValue={code} onChange={CodeChange} />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Button onClick={getCode} disabled={btnBool}>{btnText}</Button>
              </Col>
            </Row>
          </Form.Item>
          {/* 注册 */}
          <Form.Item {...tailFormItemLayout}>
            <Button type="primary" htmlType="submit" >
              注 册
            </Button>
          </Form.Item>
        </Form>
      </div>
      <Footer style={{ textAlign: 'center', backgroundColor: 'transparent' }}>
        Ant Design ©{new Date().getFullYear()} Created by Ant UED
      </Footer>
    </div>
  )
}
export default Register